/**
 * Created by zengy on 2017/6/15.
 */
angular.module('mainApp.package',['ui.router'])
    .config(function ($stateProvider) {
        $stateProvider
            .state({
                name:'package/packageList',
                url:'/package/packageList',
                templateUrl:'views/package/package_list.html?v='+new Date().getMinutes(),
                controller:'package'
            })
            .state({
                name:'package/packageDetail',
                url:'/package/packageDetail/:wxGoodsId',
                templateUrl:'views/package/package_detail.html?v='+new Date().getMinutes(),
                controller:'packageDetail'
            })
            .state({
                name:'package/packageRelation',
                url:'/package/packageRelation/:wxGoodsId',
                templateUrl:'views/package/package_relation.html?v='+new Date().getMinutes(),
                controller:'packageRelation'
            })
            .state({
                name:'package/packageAgreement',
                url:'/package/packageAgreement/:wxGoodsId',
                templateUrl:'views/package/package_agreement.html?v='+new Date().getMinutes(),
                controller:'packageAgreement'
            })
    })
    .controller('package',function ($scope) {
        $scope.$emit('arg',6)
        $scope.goodsModel={
            pageNo:1,
            pageSize:10
        }
        $scope.goodsDetailModel={};
        $scope.rowId="";
        //分页插件
        $scope.pagination = function (currentPage, pageCount) {
            $('.page-function #pagination').remove();
            $('.page-function').html('<ul id="pagination" class="pagination"></ul>');
            $('.pagination').twbsPagination({
                totalPages: pageCount,
                startPage: currentPage,
                visiblePages: 5,
                first: "首页",
                prev: "上一页",
                next: "下一页",
                last: "尾页",
                href: 'javascript:;',
                //hideOnlyOnePage : true,
                onPageClick: function (event, page) {
                    $scope.getGoodsLists(page)
                }
            });
        };
        //1.查询商品列表
        $scope.basePictureUrl=basePictureUrl;
        $scope.getGoodsLists=function (page) {
            if(page){
                $scope.goodsModel.pageNo=page;
            }
            layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
            new HttpRequest().getGoodsList($scope.goodsModel,function (res) {
                if(res.code=='000') {
                    layer.closeAll();
                    $scope.goodsList=res.data.list || [];
                    $scope.$apply();
                    if($scope.goodsList.length>0){
                        $scope.pagination($scope.goodsModel.pageNo,res.data.pageCount)
                    }
                }else{
                    layer.msg('获取商品列表失败！')
                }
            })
        }
        $scope.getGoodsLists($scope.goodsModel.pageNo);
        //上架，下架
        $scope.updateWxGoodsStatus=function (event) {
            var _this=$(event.target);
            var wxGoodsId=_this.attr('data-id');
            var status=_this.attr('data-status');
            status=(status=='0') ? '1':0;
            if(status || wxGoodsId){
                new HttpRequest().updateWxGoodsStatus({status:status,wxGoodsId:wxGoodsId},function (res) {
                    if(res.code=='000'){
                        location.reload()
                    }else{
                        layer.msg('上下架失败！')
                    }
                })
            }
        }
        //下载二维码
        $scope.getQRcode=function (event) {
            var _this=$(event.target);
            var wxGoodsId=_this.attr('data-id');
            location.href=baseUrl+'/manager/wxGoods/getQRcode?wxGoodsId='+wxGoodsId+'&pixel=200&token='+localStorage.token+'&userId='+localStorage.userId;
        }
        $scope.getfuQRcode=function (event) {
            var _this=$(event.target);
            var wxGoodsId=_this.attr('data-id');
            location.href=baseUrl+'/manager/wxGoods/getfuQRcode?wxGoodsId='+wxGoodsId+'&pixel=200&token='+localStorage.token+'&userId='+localStorage.userId;
        }
        //删除
        $scope.deleteWxGoods=function (event) {
            var _this=$(event.target);
            var wxGoodsId=_this.attr('data-id');
            if(wxGoodsId){
                var index = layer.confirm('是否要删除本条内容？', {
                    title: '删除确认',
                    btn: ['确定', '取消'],//按钮
                }, function () {
                    new HttpRequest().deleteWxGoods({wxGoodsId:wxGoodsId},function (res) {
                        if(res.code=='000'){
                            location.reload()
                        }else{
                            layer.msg('删除失败！');
                        }
                    })
                },function () {
                    layer.close(index)
                })

            }
        }

     
    })
    //编辑
    .controller('packageDetail',function ($scope,$stateParams) {
        //查看详情
        $scope.wxGoodsId=$stateParams.wxGoodsId;
        $scope.basePictureUrl=basePictureUrl;
        $scope.goodsDetailModel={}
        $scope.showPayType=false;
        new HttpRequest().getWxGoodsDetail({wxGoodsId:$scope.wxGoodsId},function (res) {
            if(res.code=='000'){
                $scope.goodsDetailModel=JSON.parse(res.data);
                editor.html($scope.goodsDetailModel.description);//详情描述
                $scope.$apply();
                $('select[name="showBalance"]').find('option[value="'+$scope.goodsDetailModel.rechargeShow+'"]').prop("selected",true);
                if($scope.goodsDetailModel.payType){
                    $('select[name="payType"]').find('option[value="'+$scope.goodsDetailModel.payType+'"]').prop("selected",true);
                }else{
                    $('select[name="payType"]').find('option:eq(1)').prop("selected",true);
                }
                if($scope.goodsDetailModel.payType && $scope.goodsDetailModel.payType=='2'){
                    $('.secondStep').show();
                }else{
                    $('.secondStep').hide();
                }

                $("body").on('change','select[name="payType"]',function () {
                  if($(this).val()=='2'){
                     $('.secondStep').show();
                  } else{
                      $('.secondStep').hide();
                    }
                })
                if($scope.goodsDetailModel.liveTime=='-1'){
                    $('select[name="timeType"]').find('option:last').prop("selected",true);
                }
               
            }
        })
        //上传封面功能
        $scope.uploadImg = function (current, type) {
            if(current.files.length>0){
                $('.imgCover').attr('src','./img/img-cover.png');
                new HttpRequest().uploadFile(current,type,function (res) {
                    if(res.code == '000'){
                        var resData = JSON.parse(res.data).url;
                        console.log(resData);
                        $scope.goodsDetailModel.coverUrl = resData;
                        $('.imgCover').attr('src',basePictureUrl+resData);
                    }else{
                        layer.msg('上传封面失败'+'('+res.msg+')');
                    }
                })
            }
        };
        //上传社区图片
        $scope.uploadGroupImg = function (current, type) {
            if(current.files.length>0){
                $('.communityPicture').attr('src','./img/img-cover.png');
                new HttpRequest().uploadFile(current,type,function (res) {
                    if(res.code == '000'){
                        var resData = JSON.parse(res.data).url;
                        console.log(resData);
                        $scope.goodsDetailModel.communityPicture = resData;
                        $('.communityPicture').attr('src',basePictureUrl+resData);
                    }else{
                        layer.msg('上传封面失败'+'('+res.msg+')');
                    }
                })
            }
        };
        //搜索医生
        var clickTime = 0;
        $('#searchDoctor').keyup(function (e) {
            var nowTime = new Date().getTime();
            if((nowTime - clickTime) < 100) return false;
            clickTime = nowTime;
            var str = $(this).val().trim();
            //空字符串跳过搜索
            if(!str){
                $('.author-list').hide();
                return false;
            }
            //按下下键方向时跳过搜索
            if(e.keyCode == 40){
                var listContainer = $('.author-list');
                var len = listContainer.children().length;
                if(!listContainer.find('.active').length){
                    listContainer.children().eq(0).addClass('active');
                }else{
                    var index = listContainer.find('.active').removeClass("active").index() + 1;
                    if(index == len) index--;
                    listContainer.children().eq(index).addClass("active");
                }
                if(index >= 6){
                    listContainer.scrollTop(listContainer.scrollTop() + listContainer.find('.active').innerHeight());
                }else{
                    listContainer.scrollTop(0);
                }
                return false;
            }
            //按下下键方向时跳过搜索
            if(e.keyCode == 38){
                var listContainer = $('.author-list');
                if(!listContainer.find('.active').length){
                    listContainer.children().eq(0).addClass('active');
                }else{
                    var index = listContainer.find('.active').removeClass("active").index() - 1;
                    if(index < 0) index = 0;
                    listContainer.children().eq(index).addClass("active");
                }
                if(index >= 6){
                    listContainer.scrollTop(listContainer.scrollTop() - listContainer.find('.active').innerHeight());
                }else{
                    listContainer.scrollTop(0);
                }
                return false;
            }
            //回车选择激活项同时跳过搜索
            if(e.keyCode == 13){
                $('.author-item.active').click();
                return false;
            }
            //搜索关键词
            new HttpRequest().searchDoctorList(str,function (res) {
                if(res.code == '000'){
                    var list =res.data;
                    var html = '';
                    for(var i =0,len=list.length;i<len;i++){
                        html += [
                            '<p class="author-item" data-id="'+ list[i].doctorRowId +'"><span class="doctor-name">'+ list[i].userName +'</span></p>'
                        ].join('');
                    }
                    $('.author-list').html(html).show();
                }
            });
        });
        $('.author-list').on('click','.author-item',function () {
            var id = $(this).attr('data-id');
            var name = $(this).find('.doctor-name').text();
            $('.author-list').hide();
            $('#searchDoctor').val('');
            if(!$('.choice-item[data-doctorId="'+ id +'"]').length){
                $('.choice-list').append('<p class="choice-item animate" data-doctorId="'+ id +'"><span>'+ name +'</span><i class="del">×</i></p>');
            }else{
                layer.msg('该成员已被添加');
            }
        });
        //保存成员列表

        $('#setMembersBtn').click(function () {
            var memberList = [];
            var html='';
            $('.choice-list .choice-item').each(function () {
                var current = $(this);
                memberList.push({
                    doctorRowId : current.attr('data-doctorId'),
                    userName : current.find('span').text(),
                });
            });
            memberList.forEach(function (val,index) {
                html+='<div class="doctor-item" data-doctorId="'+val.doctorRowId+'"> <span ng-click="delDoc($event)">&times;</span> '+val.userName+'</div>';
                $('#doctorList').html(html)
            })
            $('#choiceDoctorModal').modal('hide');

        });
        //移除列表中的成员（本地操作）
        $('.choice-list').on('click','.choice-item .del',function () {
            $(this).parents('.choice-item').remove();
        });
        $scope.delDoc=function (event) {
            var _this=$(event.target);
            _this.closest('.doctor-item').remove();
        }

        //编辑提交
        $scope.commit=function () {
            var timeType=$('select[name="timeType"]').val();
            function getLiveTime() {
                if(timeType=='1'){
                    return $scope.goodsDetailModel.liveTime*12
                }else if(timeType=='3'){
                    return '-1'
                }else{
                    return $scope.goodsDetailModel.liveTime;
                }
            }
            var doctorList=[];
            $('.doctor-item').each(function () {
                var current=$(this);
                doctorList.push(current.attr('data-doctorId'))
            })
            var param={
                rowId:$stateParams.wxGoodsId,
                doctIds:doctorList.join(","),
                name:$scope.goodsDetailModel.name,
                rechargePrice:$scope.goodsDetailModel.rechargePrice,
                liveTime:getLiveTime(),
                payType:$('select[name="payType"]').val(),
                price:$scope.goodsDetailModel.price,
                actualPrice:$scope.goodsDetailModel.actualPrice,
                earnestMoney:$scope.goodsDetailModel.earnestMoney,
                finalMoney:$scope.goodsDetailModel.finalMoney,
                coverUrl: $scope.goodsDetailModel.coverUrl,
                communityPicture:$scope.goodsDetailModel.communityPicture,
                rechargeShow:$('select[name="showBalance"]').val(),
                description:editor.html()
            }
            if($('select[name="payType"]').val() != '1'){
                if((+param.actualPrice)!=(+param.earnestMoney)+(+param.finalMoney)){
                    layer.msg('总价与定金加尾款不匹配！');
                    return false;
                }
            }

            new HttpRequest().modGoodsDetail(param,function (res) {
                if(res.code=='000'){
                    location.reload()
                }else{
                    layer.msg('修改失败！');
                }
            })
        }


    })
    .controller('packageRelation',function ($scope,$stateParams) {
        $scope.basePictureUrl=basePictureUrl;
        $scope.wxGoodsId=$stateParams.wxGoodsId;
        layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
        new HttpRequest().queryWxGoodsDetailForPackages($stateParams.wxGoodsId,function (res) {
            layer.closeAll();
            if(res.code=='000'){
                $scope.selectedList=res.data;
                $scope.$apply()
            }
        })
        new HttpRequest().otherServicesListByGoods($stateParams.wxGoodsId,function (res) {
            if(res.code=='000'){
                $scope.noSelectedList=res.data;
                $scope.$apply()
            }
        })
        $scope.addServer=function () {
            var servicesRowIds=[];
            $('input[name="servicesRowIds"]:checked').each(function () {
                var current=$(this);
                servicesRowIds.push(current.val());
            })
            //console.log(servicesRowIds)
            new HttpRequest().insertWxGoodsDetail({wxGoodsId:$stateParams.wxGoodsId,wxServicesIds:servicesRowIds.join(",")},function (res) {
                if(res.code=='000'){
                    location.reload();
                }else{
                    layer.msg('添加失败！');
                }
            })
        }
        //服务上移
        $scope.serviceMove=function (event,str) {
          var _this=$(event.target);
            var wxGoodsDetailId=_this.attr('data-id');
            new HttpRequest().upDownChange({wxGoodsDetailId:wxGoodsDetailId,upDown:str},function (res) {
                if(res.code=='000'){
                    location.reload()
                }else{
                    layer.msg(res.msg);
                }
            })
        }
        //删除服务
        $scope.serviceDel=function (event) {
            var _this=$(event.target);
            var wxServicesId=_this.attr('data-id');
            if(wxServicesId){
                var index = layer.confirm('是否要删除本条套餐服务？', {
                    title: '删除确认',
                    btn: ['确定', '取消'],//按钮
                }, function () {
                    new HttpRequest().deleteServicesByGoods({wxGoodsId:$stateParams.wxGoodsId,wxServicesId:wxServicesId},function (res) {
                        if(res.code=='000'){
                            location.reload()
                        }else{
                            layer.msg('删除失败！');
                        }
                    })
                },function () {
                    layer.close(index)
                })

            }
        }

    })
    .controller('packageAgreement',function ($scope,$stateParams) {
        $scope.wxGoodsId=$stateParams.wxGoodsId;
        new HttpRequest().getServiceAgreement({wxGoodsId:$scope.wxGoodsId},function (res) {
            if(res.code == '000'){
                editor.html(JSON.parse(res.data).serviceAgreement);//详情描述
            }
        })
        $scope.commitAgree=function () {
            var param={
                serviceAgreement:editor.html(),
                rowId:$scope.wxGoodsId
            }
            new HttpRequest().modifyWxGoodsServiceAgreement(param,function (res) {
                if(res.code != '000'){
                    layer.msg(res.msg)
                }else{
                    location.reload()
                }
            })
        }
    })



